<template>
  <div class="bind-form-container p-4">
    <!-- <h3 class="text-lg font-semibold mb-4">绑定操作</h3> -->
    <div class="mb-4">
      <p><span class="font-medium">用户ID:</span> {{ row.Id }}</p>
      <p><span class="font-medium">用户名:</span> {{ row.Name }}</p>
      <!-- 判断是否是'用户分类'进入弹窗，是的话显示，不是不显示 -->
      <p v-if="title === '用户分类'">
        <span class="font-medium">当前分类:</span>
        <span v-if="currentCategorizeName">
          {{ currentCategorizeName }}
        </span>
        <span v-else> 无分类 </span>
      </p>
      <!-- 频道绑定 -->
      <p v-if="title === '频道绑定'">
        <span class="font-medium">当前频道:</span>
        <span v-if="currentZoneName">
          {{ currentZoneName }}
        </span>
        <span v-else> 无频道 </span>
      </p>
      <!-- 设备绑定 -->
      <p v-if="title === '设备绑定'">
        <span class="font-medium">当前设备:</span>
        <span v-if="currentDeviceName">
          {{ currentDeviceName }}
        </span>
        <span v-else> 无设备 </span>
      </p>
    </div>

    <el-form ref="formRef" :model="form" label-width="100px">
      <!--用户分类-->
      <el-form-item
        v-if="title === '用户分类'"
        label="分类:"
        prop="categorizeId"
      >
        <el-select v-model="form.categorizeId" placeholder="请选择分类">
          <el-option
            v-for="option in categorizeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <!--频道绑定-->
      <el-form-item v-if="title === '频道绑定'" label="频道:" prop="zoneId">
        <el-select v-model="form.zoneId" placeholder="请选择频道">
          <el-option
            v-for="option in dynamicZoneOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <!-- 设备绑定 -->
      <el-form-item v-if="title === '设备绑定'" label="设备:" prop="deviceId">
        <el-select v-model="form.deviceId" placeholder="请选择设备">
          <el-option
            v-for="option in deviceOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit(title, props.row.Id)"
          >提交绑定</el-button
        >
        <el-button type="primary" @click="handleCancel(title, props.row.Id)"
          >解除绑定</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import type { UserItem } from "../componentsUtils/type/userTypes";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";

// 定义props
const props = defineProps<{
  row: UserItem;
  title: string;
  categorizeOptions: { label: string; value: number }[];
  zoneOptions: { label: string; value: number }[];
  deviceOptions: { label: string; value: number }[]; // 新增设备列表props
}>();

const formRef = ref();
const form = reactive<{
  categorizeId: number;
  zoneId: number;
  deviceId: number;
}>({
  categorizeId: 0,
  zoneId: 0,
  deviceId: 0
});

// 存储当前用户分类信息
const currentCategorize = ref<number>(0);
// 存储当前用户频道信息
const currentZone = ref<number>(0);
// 存储当前用户设备信息
const currentDevice = ref<number>(0);
// 动态频道选项数据
const dynamicZoneOptions = ref<{ label: string; value: number }[]>([]);
// 计算当前分类名称
const currentCategorizeName = computed(() => {
  if (currentCategorize.value === 0) {
    return "";
  }
  const option = props.categorizeOptions.find(
    opt => opt.value === currentCategorize.value
  );
  return option ? option.label : "";
});
// 计算当前频道名称
const currentZoneName = computed(() => {
  if (currentZone.value === 0) {
    return "";
  }
  const option = dynamicZoneOptions.value.find(
    opt => opt.value === currentZone.value
  );
  return option ? option.label : "";
});
// 计算当前设备名称
const currentDeviceName = computed(() => {
  if (currentDevice.value === 0) {
    return "";
  }
  const option = props.deviceOptions.find(
    opt => opt.value === currentDevice.value
  );
  return option ? option.label : "";
});
// 获取用户分类信息
const getUserCategorize = async () => {
  if (props.title !== "用户分类" || !props.row?.Id) {
    return;
  }

  const loading = ElMessage({
    message: "获取分类信息中...",
    duration: 0
  });

  try {
    const res: any = await http.get(
      changeHttpLink(`/api/User/${props.row.Id}/categorize`)
    );
    console.log("用户分类信息", res);
    if (res.Success && res.Data) {
      // 根据实际接口返回的数据格式修改，使用Id作为分类ID
      const categorizeId = res.Data.Id || 0;
      // 可以额外存储分类名称
      const categorizeName = res.Data.Name || "";

      console.log(`获取到用户分类: ID=${categorizeId}, Name=${categorizeName}`);

      currentCategorize.value = categorizeId;
      form.categorizeId = categorizeId;
    } else {
      ElMessage.error("未绑定用户分类");
    }
  } catch (err) {
    console.error("获取用户分类信息失败:", err);
    ElMessage.error("获取用户分类信息失败，请重试");
  } finally {
    loading.close();
  }
};
// 获取用户频道信息
const getUserChannel = async () => {
  if (props.title !== "频道绑定" || !props.row?.Id) {
    return;
  }

  const loading = ElMessage({
    message: "获取频道信息中...",
    duration: 0
  });
  const params = {
    id: props.row.Id
  };
  try {
    const res: any = await http.get(
      changeHttpLink(`/api/ChannelMember/user/${props.row.Id}/channels`),
      {
        params
      }
    );
    console.log("用户频道信息", res);
    //根据ChannelId获取频道名称
    if (res.Success && res.Data && res.Data.length > 0) {
      // 从API返回数据中获取ChannelId
      const channelId = res.Data[0].ChannelId || 0;

      // 设置表单默认值
      form.zoneId = channelId;
      currentZone.value = channelId;

      console.log(`获取到用户频道: ChannelId=${channelId}`);
    } else {
      ElMessage.error("未绑定频道");
    }
  } catch (err) {
    console.error("获取用户频道信息失败:", err);
    ElMessage.error("获取用户频道信息失败，请重试");
  } finally {
    loading.close();
  }
};
// 获取用户设备信息
const getUserDevice = async () => {
  if (props.title !== "设备绑定" || !props.row?.Id) {
    return;
  }

  const loading = ElMessage({
    message: "获取设备信息中...",
    duration: 0
  });

  try {
    const res: any = await http.get(
      changeHttpLink(`/api/User/${props.row.Id}/device`)
    );
    console.log("用户设备信息", res);
    if (res.Success && res.Data) {
      // 假设设备接口返回格式与分类类似，使用Id作为设备ID
      const deviceId = res.Data.Id || 0;
      const deviceName = res.Data.Name || "";

      console.log(`获取到用户设备: ID=${deviceId}, Name=${deviceName}`);

      currentDevice.value = deviceId;
      form.deviceId = deviceId;
    } else {
      ElMessage.error(res.Message || "获取设备信息失败");
    }
  } catch (err) {
    console.error("获取用户设备信息失败:", err);
    ElMessage.error("获取用户设备信息失败，请重试");
  } finally {
    loading.close();
  }
};
onMounted(async () => {
  console.log("绑定操作", props.title);
  // 进入弹窗时获取对应信息
  if (props.title === "用户分类") {
    getUserCategorize();
  } else if (props.title === "频道绑定") {
    // 获取频道选项数据
    dynamicZoneOptions.value = await getChannelOptions(props.row.TenantId);
    getUserChannel();
  } else if (props.title === "设备绑定") {
    getUserDevice();
  }
});

// 提交绑定
function handleSubmit(title: string, Id: number) {
  // 这里添加表单验证和提交逻辑
  console.log(title, form, Id);
  console.log("用户ID", Id);
  // 添加加载状态
  const loading = ElMessage({
    message: "处理中...",
    duration: 0
  });
  switch (title) {
    case "用户分类":
      console.log(title);
      console.log("用户ID", Id);
      console.log(form.categorizeId);
      //设置用户分类
      http
        .post(changeHttpLink(`/api/User/set-categorize`), {
          data: {
            id: Id,
            categorizeId: form.categorizeId
          }
        })

        .then((res: any) => {
          console.log(res);
          if (res.Success) {
            ElMessage.success("用户分类设置成功");
            // 可以在这里添加关闭对话框的逻辑
          } else {
            ElMessage.error(res.Message || "设置失败");
          }
        })
        .catch(err => {
          console.error("设置用户分类失败:", err);
          ElMessage.error("设置用户分类失败，请重试");
        })
        .finally(() => {
          loading.close();
        });

      break;
    case "频道绑定":
      const params = {
        dealerId: props.row.DealerId,
        tenantId: props.row.TenantId,
        channelId: form.zoneId,
        userId: Id,
        priority: 5
      };
      //设置用户频道绑定
      console.log("params", params);
      http
        .post(changeHttpLink(`/api/ChannelMember`), { data: params })
        .then((res: any) => {
          if (res.Success) {
            ElMessage.success("频道绑定设置成功");
          } else {
            ElMessage.error(res.Message || "设置失败");
          }
        })
        .catch(err => {
          console.error("设置频道绑定失败:", err);
          ElMessage.error("设置频道绑定失败，请重试");
        })
        .finally(() => {
          loading.close();
        });

      break;
    case "设备绑定":
      console.log(title);
      console.log("用户ID", Id);
      console.log(form.deviceId);
      //设置用户设备
      http
        .post(changeHttpLink(`/api/User/link-device`), {
          data: {
            id: Id,
            deviceId: form.deviceId
          }
        })
        .then((res: any) => {
          if (res.Success) {
            ElMessage.success("设备绑定设置成功");
          } else {
            ElMessage.error(res.Message || "设置失败");
          }
        })
        .catch(err => {
          console.error("设置设备绑定失败:", err);
          ElMessage.error("设置设备绑定失败，请重试");
        })
        .finally(() => {
          loading.close();
        });

      break;
    default:
      break;
  }
}
// 取消绑定
function handleCancel(title: string, Id: number) {
  // 添加加载状态
  const loading = ElMessage({
    message: "取消绑定中...",
    duration: 0
  });

  switch (title) {
    case "用户分类":
      console.log("取消用户分类", Id);
      // 取消用户分类API调用框架
      http
        .post(changeHttpLink(`/api/User/set-categorize`), {
          data: {
            id: Id,
            categorizeId: 0 // 参数固定为0
          }
        })
        .then((res: any) => {
          if (res.Success) {
            ElMessage.success("用户分类取消成功");
          } else {
            ElMessage.error(res.Message || "取消失败");
          }
        })
        .catch(err => {
          console.error("取消用户分类失败:", err);
          ElMessage.error("取消用户分类失败，请重试");
        })
        .finally(() => {
          loading.close();
        });
      break;
    case "频道绑定":
      console.log("取消频道绑定", Id);
      console.log("频道ID", form.zoneId);
      // 取消区域绑定API调用
      http
        .post(changeHttpLink(`/api/Channel/remove-member`), {
          data: {
            id: form.zoneId,
            userId: Id // 参数userId为用户ID
          }
        })
        .then((res: any) => {
          if (res.Success) {
            ElMessage.success("频道绑定取消成功");
          } else {
            ElMessage.error(res.Message || "取消失败");
          }
        })
        .catch(err => {
          console.error("取消频道绑定失败:", err);
          ElMessage.error("取消频道绑定失败，请重试");
        })
        .finally(() => {
          loading.close();
        });
      break;
    case "设备绑定":
      console.log("取消设备绑定", Id);
      // 取消设备绑定API调用
      http
        .post(changeHttpLink(`/api/User/${Id}/unlink-device`))
        .then((res: any) => {
          if (res.Success) {
            ElMessage.success("设备绑定取消成功");
          } else {
            ElMessage.error(res.Message || "取消失败");
          }
        })
        .catch(err => {
          console.error("取消设备绑定失败:", err);
          ElMessage.error("取消设备绑定失败，请重试");
        })
        .finally(() => {
          loading.close();
        });
      break;
    default:
      loading.close();
      break;
  }
}
//获取频道下拉列表
const getChannelOptions = async (lesseeId: number) => {
  try {
    const res: any = await http.get(changeHttpLink("/api/Channel"), {
      params: {
        PageSize: 1000,
        PageIndex: 1,
        tenantId: lesseeId
      }
    });
    console.log("频道下拉列表", res);
    if (res.Success && res.Data && res.Data.Items) {
      return res.Data.Items.map((item: any) => ({
        label: item.Name || item.label,
        value: item.Id || item.value
      }));
    }
    return [];
  } catch (err) {
    console.error("获取频道下拉列表失败:", err);
    ElMessage.error("获取频道下拉列表失败，请重试");
    return [];
  }
};
</script>

<style scoped>
.bind-form-container {
  width: 100%;
}
</style>
